package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Resource
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Resource
    private  ApArticleService apArticleService;

    /**
     * 生成静态文件保存到MinIO中
     *
     * @param article
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle article, String content) {
        //获取文章内容
        if (StringUtils.isNoneBlank(content)) {
            Template template=null;
            StringWriter put=new StringWriter();
        //将文章内容通过fremarker模板生成
            try {
                template=configuration.getTemplate("article.ftl");
                //数据模型
                Map<String,Object> contentMap=new HashMap<>();
                contentMap.put("content", JSONArray.parseArray(content));


                //合成
                template.process(contentMap,put);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            InputStream in=new ByteArrayInputStream(put.toString().getBytes());
            String path=fileStorageService.uploadHtmlFile("",article.getId()+".html", in);

            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId, article.getId())
                    .set(ApArticle::getStaticUrl,path));


            //发送消息，创建索引
            createArticleESIndex(article,content,path);
        }

    }

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 送消息，创建索引
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }
}
